package org.hq.controller;
import org.hq.pojo.LoginUser;
import org.hq.pojo.WebUser;
import org.hq.service.TokenService;
import org.hq.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping
public class Myuser {
    @Autowired
    private AuthenticationManager am;
    @Autowired
    private TokenService ts;

    @PostMapping("/logintojson")
    public R<String> llssdd(String username, String password) {
        System.out.println("登录系统用户 " + username);
        try {
            // 封装登录系统用户
            UsernamePasswordAuthenticationToken upa = new UsernamePasswordAuthenticationToken(username, password);
            //认证处理
            Authentication authenticate = am.authenticate(upa);
            //判断是否认证成功
            //将认证用户保存到上下文去
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            // 获取系统登录用户保存到redis
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            WebUser user = loginUser.getUser();
            // long time= 5L * TimeUnit.MINUTES;

            //保存 token
            user.setPassword(password);
            String token = ts.saveToken(user, 600);
            return R.ok(token);
        } catch (Exception e) {

        }

        return R.no();
    }

    @GetMapping("/qwert")
    public String getmyuser() {
        System.out.println("反反复复嘎嘎嘎嘎嘎嘎嘎嘎嘎嘎嘎嘎的");


        return null;
    }

}
